package com.easymin.weixin.common;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import com.easymin.weixin.common.api.DaijiaApi;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

public class CommonUtil {
  
  private static final Logger logger = LoggerFactory.getLogger(CommonUtil.class);
  
  /**
   * 上传跑腿订单图片.
   */
  
  @RequestMapping(method = RequestMethod.POST, value = "uploaderrandimg")
  public static String uploadErrandImg(
      @RequestParam("photo") MultipartFile imgFile,
      HttpServletRequest req) throws IOException {
    
    String moduleName = imgFile.getOriginalFilename();
    if (MediaUtil.isPicture(moduleName, "")) {
      String bathPath = getBasePath(req);
      Date now = new Date();
      String filestr = "upload/photos/" + now.getTime() 
          + moduleName.substring(moduleName.lastIndexOf("."), moduleName.length());
      File file = new File(bathPath, filestr);

      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }

      try {
        File tempDest = new File(System.getProperty("java.io.tmpdir"),
            "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
        imgFile.transferTo(tempDest); //上传到临时文件中
        FileUtils.copyFile(tempDest, file);
        tempDest.delete();
        return filestr;
      } catch (Exception ex) {
        logger.error(ex.getMessage());
        return "";
      }
    } else {

      String bathPath = getBasePath(req);
      Date now = new Date();
      String filestr = "upload/voice/" + now.getTime() 
          + moduleName.substring(moduleName.lastIndexOf("."), moduleName.length());
      File file = new File(bathPath, filestr);

      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }

      try {
        File tempDest = new File(System.getProperty("java.io.tmpdir"), 
            "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
        imgFile.transferTo(tempDest); //上传到临时文件中
        FileUtils.copyFile(tempDest, file);
        tempDest.delete();
        return filestr;
      } catch (Exception ex) {
        logger.error(ex.getMessage());
        return "";
      }

    }

  }

  private static String getBasePath(HttpServletRequest req) {

    try {
      return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
    } catch (FileNotFoundException ex) {
      logger.error(ex.getMessage());
    }

    return StringUtils.EMPTY;
  }
}
